package com.pkk.penguin.frame.know.boot.view.controller.zydb;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pkk.components.rpc.request.CommonRequest;
import com.pkk.components.rpc.response.CommonResponse;
import com.pkk.components.rpc.response.util.ResponseUtil;
import com.pkk.penguin.frame.know.boot.config.common.handle.AbstractWebSocketServer;
import com.pkk.penguin.frame.know.boot.config.common.handle.AbstractWebSocketServer.WebScoketUtil;
import com.pkk.penguin.frame.know.boot.config.handle.zhiyi.db.ZyDbWebSocketServer;
import com.pkk.penguin.frame.know.boot.config.handle.zhiyi.db.support.support.ExecPingTaiSingleSupport;
import com.pkk.penguin.frame.know.boot.config.handle.zhiyi.db.support.util.ExecUtil;
import com.pkk.penguin.frame.know.boot.view.controller.common.AbstractAppletController;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @description: 之易数据库控制器
 * @author: peikunkun
 * @create: 2020-06-01 13:52
 **/
@Slf4j
@RestController
@RequestMapping("zyDb")
public class ZyDbAppletController extends AbstractAppletController {


  @Resource
  private ZyDbWebSocketServer zyDbWebSocketServer;


  @Value("${com.pkk.config.zhiyi.db.logpath}")
  private String execLogPath;

  /**
   * @Description: 执行
   * @Param: request
   * @return: com.pkk.components.rpc.response.CommonResponse<java.lang.Boolean>
   * @Author: peikunkun
   * @Date: 2020/6/1 0001 下午 3:31
   */
  @RequestMapping("exec")
  public CommonResponse<Boolean> exec(@RequestBody CommonRequest<JSONObject> request) {
    final JSONObject body = request.getBody();
    final String command = body.getString("command");
    final String debuglog = body.getString("debuglog");
    final JSONArray execPlatforms = body.getJSONArray("platforms");
    if (StringUtils.isBlank(command)) {
      return ResponseUtil.error("请输入要执行的命令");
    }
    if (null == execPlatforms || execPlatforms.size() <= 0) {
      return ResponseUtil.error("请选择平台");
    }
    log.info("[同步之易数据]-{}", body);
    Long begin = System.currentTimeMillis();
    final ExecPingTaiSingleSupport instance = ExecPingTaiSingleSupport.getInstance();

    //支持的平台
    final Set<String> supportPingTai = ExecUtil.PINGTAI_KEY_INFO.keySet();
    final Set<String> execPingtai = execPlatforms.stream().map(e -> e.toString()).collect(Collectors.toSet());

    StringBuffer sb = new StringBuffer("------------------------------------\n");
    Set<String> diffSet = new HashSet<>(execPingtai);
    diffSet.removeAll(execPingtai);
    if (diffSet.size() > 0) {
      sb.append("[不支持的平台]:" + JSONObject.toJSONString(diffSet));
    }

    //交集支持的平台
    Set<String> mixedSet = new HashSet<>(supportPingTai);
    mixedSet.retainAll(execPingtai);

    final JSONArray exec = instance.execPlus(mixedSet, command, true, zyDbWebSocketServer);
    for (int i = 0; i < exec.size(); i++) {
      log.info(JSONObject.toJSONString(exec.getJSONObject(i)));
      if ("1".equals(debuglog)) {
        sb.append(JSONObject.toJSONString(exec.getJSONObject(i)));
      }
    }
    Long end = System.currentTimeMillis();

    final String format = DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN);
    final String execLogFilePath = execLogPath.substring(0, execLogPath.lastIndexOf(".")).concat("-" + format)
        .concat(execLogPath.substring(execLogPath.lastIndexOf(".")));
    final String execLog = ExecUtil.appentExeSQL(execLogFilePath, (end - begin), exec);
    sb.append("执行结果:" + execLog);
    sb.append("------------------------------------\n\n");
    System.out.println("【更新数据库】\n" + log.toString());
    WebScoketUtil.broadcostOperate(zyDbWebSocketServer.getWebSocket(), sb.toString());
    return ResponseUtil.success(true);
  }

  /**
   * @Description: 获取webSocketServer
   * @Param:
   * @return: java.util.concurrent.ConcurrentHashMap<java.lang.String, com.pkk.penguin.frame.know.boot.config.common.handle.AbstractWebSocketServer>
   * @Author: peikunkun
   * @Date: 2020/6/1 0001 下午 2:07
   */
  @Override
  protected ConcurrentHashMap<String, AbstractWebSocketServer> getWebSocketServer() {
    return zyDbWebSocketServer.getWebSocket();
  }

  /**
   * @Description: 处理平台列表
   * @Param:
   * @return: com.alibaba.fastjson.JSONArray
   * @Author: peikunkun
   * @Date: 2020/6/1 0001 下午 2:04
   */
  @Override
  protected JSONArray handlePlatformList() {
    return JSONArray.parseArray(JSONObject.toJSONString(ExecUtil.PINGTAI_KEY_INFO.keySet()));
  }
}
